package com.xphuong.newskios;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ListView;

import com.xphuong.adapter.NewsListAdapter;
import com.xphuong.newskios.util.Util;
import com.xphuong.task.LoadNewsTask;

public class NewsListActivity extends Activity {

	private NewsListAdapter mAdapter;
	private ListView mNewsLst;

	private ProgressDialog dialog;

	private String mLink = "";
	private boolean isLoaded;

	final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if (msg.what == Util.LOAD_NEWS_TASK) {
				if (msg.arg1 == LoadNewsTask.RESULT_OK) {
					isLoaded = true;
				} else if (msg.arg1 == LoadNewsTask.RESULT_FAIL) {
					isLoaded = false;
				}

				loadData();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_newslist);

		Intent intent = getIntent();
		mLink = intent.getStringExtra(Util.TOPIC_LINK);

		loadData();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		if (dialog != null)
			dialog.dismiss();

		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		if (dialog != null)
			dialog.dismiss();

		super.onPause();
	}

	public void loadNewsView() {
		setContentView(R.layout.activity_newslist);

		mAdapter = new NewsListAdapter(this, Util.lstNews);
		mNewsLst = (ListView) findViewById(R.id.newslist_list);
		mNewsLst.setAdapter(mAdapter);
	}

	public void loadData() {
		if (isLoaded) {
			dialog.dismiss();
			loadNewsView();
		} else {
			if (Util.isNetworkAvaiable(this)) {
				dialog = ProgressDialog.show(this, "", "Loading...");
				new LoadNewsTask(handler).execute(mLink);
			} else
				finish();
		}
	}
}
